package com.jianganming.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器式单例，Spring的核心
 */
public class ContainerSingleton {
    private ContainerSingleton(){}
    private static Map<String,Object> singletonMap = new ConcurrentHashMap<>();
    public static Object getInstance(Class clazz)throws Exception{
        String name = clazz.getName();
        if(!singletonMap.containsKey(name)){
            Object o = Class.forName(name).newInstance();
            singletonMap.put(name,o);
            return o;
        }
        return singletonMap.get(name);
    }
    public static void main(String[] args)throws Exception {
        Object instance1 = getInstance(Singleton2.class);
        Object instance2 = getInstance(Singleton2.class);
        System.out.println(instance1);
        System.out.println(instance2);
    }
}
